package com.spring.arch.common.db;

import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

@Getter
class JdbcUrlSplitter {
    private String driverName;
    private String host;
    private String port;
    private String database;
    private String params;

    JdbcUrlSplitter(String jdbcUrl) {
        int pos, pos1, pos2;
        String connUri;

        if (jdbcUrl == null || !jdbcUrl.startsWith("jdbc:")
                || (pos1 = jdbcUrl.indexOf(':', 5)) == -1) {
            throw new IllegalArgumentException("Invalid JDBC url.");
        }

        driverName = jdbcUrl.substring(5, pos1);

        // 参数开始位置
        pos2 = StringUtils.indexOfAny(jdbcUrl, "?;");
        if ((pos2) == -1) {
            connUri = jdbcUrl.substring(pos1 + 1);
        } else {
            connUri = jdbcUrl.substring(pos1 + 1, pos2);
            params = jdbcUrl.substring(pos2 + 1);
        }

        if (connUri.startsWith("//")) {
            if ((pos = connUri.indexOf('/', 2)) != -1) {
                host = connUri.substring(2, pos);
                database = connUri.substring(pos + 1);

                if ((pos = host.indexOf(':')) != -1) {
                    port = host.substring(pos + 1);
                    host = host.substring(0, pos);
                }
            }
        } else {
            database = connUri;
        }
    }
}